//
//  Status.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/30.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import SDWebImage


///访问微博首页URL
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class Status: NSObject {
    
    //MARK: - 数据模型属性
    ///微博创建时间
    var created_at: String?
    ///微博ID
    var id: Int = 0
    ///微博信息内容
    var text: String?
    ///微博来源
    var source: String? {
        didSet{
            if let result = source?.hrefLink() {
                source = result.text
            }
        }
    }
    ///配图数组
    var pic_urls: [[String: String]]? {
        didSet {
            imageURLs = [NSURL]()
            largeImageURLs = [NSURL]()
            
            //生成并添加URL
            for dict in pic_urls! {
                //缩略图
                var urlString = dict["thumbnail_pic"]!
                imageURLs?.append(NSURL(string:urlString)!)
                //大图
                urlString = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                largeImageURLs?.append(NSURL(string: urlString)!)
                
            }
        }
        
    }
    
    ///配图的URL数组
    private var imageURLs: [NSURL]?
    ///计算行属性
    var pictureURLs: [NSURL]? {
        return retweeted_status != nil ? retweeted_status?.imageURLs : imageURLs
    }
    
    ///大图的URL数组
    private var largeImageURLs: [NSURL]?
    var largePicURLs: [NSURL]? {
        return retweeted_status != nil ?retweeted_status?.largeImageURLs : largeImageURLs
    }
    
    ///用户模型
    var user: User?
    
    ///转发微博
    var retweeted_status: Status?
    
    //类属性数组
    static let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    
    ///字典转模型函数
    init(dict: [String: AnyObject]) {
        super.init()
        
        for key in Status.properties {
            
            if dict[key] == nil || key == "user" || key == "retweeted_status" {
                continue;
            }
            setValue(dict[key], forKey: key)
        }
        //判断字典中是否包含user
        if let userDict = dict["user"] as? [String: AnyObject]{
            user = User(dict: userDict)
        }
        //判断字典中是否包含 retweeted_status
        if let retweetedDict = dict["retweeted_status"] as? [String: AnyObject]{
            retweeted_status = Status(dict: retweetedDict)
        }

        
    }
    override var description: String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
    
    ///加载数据
    class func loadStatus(since_id: Int, max_id: Int, finished: (statuses: [Status]?, error: NSError?) -> ()) {
        assert(sharedUserAccount != nil, "必须登录后才能访问网络")
        
        var params = ["access_token":sharedUserAccount!.access_token]
        
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            params["since_id"] = "0"
            params["max_id"] = "\(max_id - 1)"
        }
        
        //发起网络请求
        NetworkTools.sharedNetworkTools().GET(WB_Home_Timeline_URL, parameters: params, success: { (_, JSON) -> Void in
            
            //从结果中取出微博数组
            if let array = JSON["statuses"] as? [[String: AnyObject]] {
                //1. 获取微博的模型数组
                let list = statuses(array)
                
                cacheWebImage(list, finished: finished)
            }
            
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    ///缓存微博数组中的所有图片
    private class func cacheWebImage(list: [Status],finished: (status: [Status]?, error: NSError?) -> ()) {
        //1. 定义调度组
        let group = dispatch_group_create()
        
        //2. 遍历数组
        for status in list {
            if status.pictureURLs == nil || status.pictureURLs!.isEmpty {
                continue
            }
            //print(status.pictureURLs)
            //进一步遍历pictureURLs数组，缓存图片
            for url in status.pictureURLs! {
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 代码执行到此，说明图片已经被缓存完成
                    //print(NSHomeDirectory())
                    
                    //离开组
                    dispatch_group_leave(group)
                })
            }
            
        }
        //监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存结束！！！")
            finished(status: list, error: nil)
        }
    }
    
    //使用传入的数组，完成网络模型status数组
    private class func statuses(array: [[String: AnyObject]]) -> [Status] {
        
        //定义可变数组
        var arrayM = [Status]()
        //遍历array
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
        return arrayM
        
    }

}
